package com.etong.citymap.activity;

import android.Manifest;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;

import com.etong.citymap.connect.HttpSendData;
import com.etong.citymap.db.util.CityApplication;
import com.etong.citymap.service.UploadSerivice1;
import com.etong.citymap.util.ActivityUtil;
import com.etong.citymap.util.NetConnectionState;
import com.etong.citymap.util.PermissionsUtils;
import com.etong.citymap.util.Status;
import com.etong.citymap.util.StringUtil;
import com.etong.citymap.util.log.LogUtil;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.Map;

/**
 * 登录界面、包括权限设置
 */
public class LoginActivity extends Activity implements OnClickListener {
	private EditText username;
	private EditText passworld;
	private LinearLayout login_btu;
	public static String UserName = "username";
	private static String UserPass = "passworld";
	public static String UserId = "userid";
	public static String UserCode = "usercode";
	private static String ZFTName = "zft";
	private static boolean isZFT = false;

	boolean isZhiFaTong = false;

	private CityApplication cityApplication;

	LinearLayout login_zft;
	LinearLayout login_jzmm;
	CheckBox login_jzmm_check;
	CheckBox login_zft_check;
	AlertDialog dialog;
	SharedPreferences sharedPreferences;
	Handler handler = new Handler(new Handler.Callback() {

		@Override
		public boolean handleMessage(Message msg) {
			if (msg.what == 1) {
				dialog.dismiss();
				String result = msg.getData().getString("result");
				resultJudge(result);
			}
			return false;
		}
	});

	//创建监听权限的接口对象
	PermissionsUtils.IPermissionsResult permissionsResult = new PermissionsUtils.IPermissionsResult() {
		@Override
		public void passPermissons() {
			//权限通过执行的方法
			//权限通过验证
		}

		@Override
		public void forbitPermissons() {
			//这是没有通过权限的时候提示的内容，自定义即可
			Toast.makeText(getApplication(), "您没有允许部分权限，可能会导致部分功能不能正常使用，如需正常使用  请允许权限", Toast.LENGTH_LONG).show();
			finish();
		}
	};

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);

		getPermission();
		LogUtil.registUtil(getApplicationContext());

		cityApplication = (CityApplication) getApplication();
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_login);
		sharedPreferences = this.getSharedPreferences("data", Context.MODE_PRIVATE);
		init();
		// Configure.HTTPURL=sharedPreferences.getString(MainActivity.HttpShareUrl,
		// Configure.HTTPURL);
		cityApplication.setHTTPURL(sharedPreferences.getString(MainActivity.HttpShareUrl, cityApplication.getHTTPURL()));
		String user = sharedPreferences.getString(UserName, "");
		String mima = sharedPreferences.getString(UserPass, "");
		isZFT = sharedPreferences.getBoolean(ZFTName, false);
		if (isZFT) {
			login_zft_check.setChecked(true);
		}
		if (StringUtil.IsNotNull(user)) {
			username.setText(user);
			login_jzmm_check.setChecked(true);
		}
		if (StringUtil.IsNotNull(mima)) {
			passworld.setText(mima);
		}
		// PandDuan();
	}

	public void savemmzh() { // 保存到SharedPreferences
		Editor editor = sharedPreferences.edit();
		if (login_jzmm_check.isChecked()) {
			editor.putString(UserName, username.getText().toString());
			editor.putString(UserPass, passworld.getText().toString());
			editor.putString(UserId, cityApplication.getUserId());
			editor.putString(UserCode, cityApplication.getUserCode());
		} else {
			editor.putString(UserName, "");
			editor.putString(UserPass, "");
		}
		if (login_zft_check.isChecked()) {
			editor.putBoolean(ZFTName, true);
		} else {
			editor.putBoolean(ZFTName, false);
		}
		editor.commit();
	}

	void init() {
		username = (EditText) findViewById(R.id.username);
		passworld = (EditText) findViewById(R.id.userpwd);
		login_btu = (LinearLayout) findViewById(R.id.login_btu);
		login_zft = (LinearLayout) findViewById(R.id.login_zft);
		login_zft_check = (CheckBox) findViewById(R.id.login_zft_check);
		login_jzmm = (LinearLayout) findViewById(R.id.login_jzmm);
		login_jzmm_check = (CheckBox) findViewById(R.id.login_jzmm_check);
		login_zft.setOnClickListener(this);
		login_jzmm.setOnClickListener(this);
		login_btu.setOnClickListener(this);
		dialog = new ProgressDialog(this);
		dialog.setTitle(null);
		dialog.setMessage("登录验证中...");
		dialog.setCanceledOnTouchOutside(false);

	}

	public void PandDuan() { // 判断IMIS卡的类型
		int result = NetConnectionState.GetIMSI(this);
		if (result == -1) {
			Toast.makeText(this, "获取IMSI出错", Toast.LENGTH_SHORT).show();
		} else {
			if (result != Status.IMSI_DX) {
				Toast.makeText(this, "此软件为电信手机专用", Toast.LENGTH_SHORT).show();
//				System.exit(0);
			}
		}
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		getMenuInflater().inflate(R.menu.activity_city, menu);
		return true;
	}

	@Override
	public void onClick(View v) {
		if (login_btu == v) {
			if (StringUtil.IsNotNull(username.getText().toString())
					&& StringUtil.IsNotNull(passworld.getText().toString())) {
				dialog.show();
				savemmzh();
				if (login_zft_check.isChecked()) {
					isZhiFaTong = true;
				} else {
					isZhiFaTong = false;
				}
				new Login().start();
			} else {
				Toast.makeText(this, "用户名或密码不能为空", Toast.LENGTH_SHORT).show();
			}

		}
		if (login_jzmm == v) {
			if (login_jzmm_check.isChecked()) {
				login_jzmm_check.setChecked(false);
			} else {
				login_jzmm_check.setChecked(true);
			}
		}
		if (login_zft == v) {
			if (login_zft_check.isChecked()) {
				login_zft_check.setChecked(false);
			} else {
				login_zft_check.setChecked(true);
			}
		}

	}

	class Login extends Thread { // 登陆
		@Override
		public void run() {
			String url = "supervisor/ashx/login.ashx"; // 001 001
			Map<String, String> map = new HashMap<String, String>();
			if (isZhiFaTong) {
				url = "supervisor/ashx/czlogin.ashx";
				map.put("username", username.getText().toString());
				map.put("userpass", passworld.getText().toString());
			} else {
				map.put("supername", username.getText().toString());
				map.put("superpass", passworld.getText().toString());
			}
			try {
				String result = HttpSendData.SendGet(url, map, "utf-8", cityApplication.getHTTPURL());
				Message message = new Message();
				message.what = 1;
				Bundle bundle = message.getData();
				bundle.putString("result", result);
				handler.sendMessage(message);
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}

	}

	private void resultJudge(String result) { // 判断结果
		if (result == null) {
			Toast.makeText(LoginActivity.this, "网络连接错误，无法连接服务器！", Toast.LENGTH_SHORT).show();
		} else if (result.equals("-2")) {
			Toast.makeText(LoginActivity.this, "登陆失败，请确认用户名和密码正确。", Toast.LENGTH_SHORT).show();
		} else if (result.equals("-3")) {
			Toast.makeText(LoginActivity.this, "上传的参数有误！", Toast.LENGTH_SHORT).show();
		} else {
			LogUtil.e("通过resultJudge判断登录成功！");
			CityApplication.realLogout = false;
			try {
				JSONObject jsonObject = new JSONObject(result);
				if (isZhiFaTong) {
					cityApplication.setZFTUserName(jsonObject.getString("username"));
					cityApplication.setZFTUserId(jsonObject.getString("userid"));
					cityApplication.setZFTOrgId(jsonObject.getString("orgid"));
					/*
					 * Configure.ZFTUserName = jsonObject.getString("username");
					 * Configure.ZFTUserId = jsonObject.getString("userid");
					 * Configure.ZFTOrgId = jsonObject.getString("orgid");
					 */
					savemmzh();
					ActivityUtil.ToActivity(LoginActivity.this, LawEnforcementActivity.class);
				} else {
					cityApplication.setUserId(jsonObject.getString("id"));
					cityApplication.setUserCode(jsonObject.getString("code"));
					cityApplication.setUserName(username.getText().toString());
					/*
					 * Configure.UserId = jsonObject.getString("id");
					 * Configure.UserCode = jsonObject.getString("code");
					 * Configure.UserName=username.getText().toString();
					 */
					savemmzh();
					ActivityUtil.ToActivity(LoginActivity.this, MainActivity.class);
					startService(new Intent(LoginActivity.this, UploadSerivice1.class));
				}
				finish();
			} catch (Exception e) {
				LogUtil.e(e);
			}
		}

	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		return true;
	}

	private void getPermission() {
		//两个日历权限和一个数据读写权限
		String[] permissions = new String[]{Manifest.permission.VIBRATE,
				Manifest.permission.ACCESS_COARSE_LOCATION,
				Manifest.permission.ACCESS_FINE_LOCATION,
				//Manifest.permission.ACCESS_BACKGROUND_LOCATION,
				Manifest.permission.INTERNET,
				Manifest.permission.READ_EXTERNAL_STORAGE,
				Manifest.permission.WRITE_EXTERNAL_STORAGE,
				Manifest.permission.ACCESS_NETWORK_STATE,
				Manifest.permission.ACCESS_WIFI_STATE,
				Manifest.permission.CHANGE_WIFI_STATE,
				Manifest.permission.READ_PHONE_STATE,
				Manifest.permission.CAMERA,
				Manifest.permission.READ_CONTACTS,
				Manifest.permission.WRITE_CONTACTS,
				//Manifest.permission.REQUEST_INSTALL_PACKAGES,
				//Manifest.permission.SYSTEM_ALERT_WINDOW,
				Manifest.permission.CALL_PHONE
		};

		PermissionsUtils.showSystemSetting = true;//是否支持显示系统设置权限设置窗口跳转
		//这里的this不是上下文，是Activity对象！
		PermissionsUtils.getInstance().chekPermissions(this, permissions, permissionsResult);
	}

	@Override
	public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
		super.onRequestPermissionsResult(requestCode, permissions, grantResults);
		//就多一个参数this
		PermissionsUtils.getInstance().onRequestPermissionsResult(this, requestCode, permissions, grantResults);
	}

}
